package Dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import pojo.Book;
import pojo.Record;
import util.DBUtil;

public class RecordDaoImpl implements RecordDao{

	public int addRecord(Record r) {
		String sql="insert into records(rid,bid,uuid,amount,rdate)values(?,?,?,?,?)";
		Connection conn=null;
		PreparedStatement pst =null;
		ResultSet rs = null;
		String rid = UUID.randomUUID().toString();
		int m = 0;
		try {
			conn=DBUtil.createConnection();
			pst=conn.prepareStatement(sql);
			pst.setString(1, rid);
			pst.setString(2, r.getBid());
			pst.setString(3, r.getUuid());
			pst.setInt(4, r.getAmount());
			pst.setDate(5, new java.sql.Date(r.getRdate().getTime()));
			m = pst.executeUpdate();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally{
			DBUtil.close(conn, pst, null);
		}
		System.out.println(m);
		return m;
	}

	public List<Record> loadRecordsByuuid(String uuid) {
		List<Record> rl = new ArrayList<Record>();
		String sql="select * from records where uuid = ?";
		PreparedStatement pst =null;
		ResultSet rs = null;
		Connection conn = null;
		Record r =null;
		int m =0;
		try {
			conn=DBUtil.createConnection();
			pst=conn.prepareStatement(sql);
			pst.setString(1,uuid);
			rs=pst.executeQuery();
			while(rs.next()){
				r= new Record();
				r.setRid(rs.getString("rid"));
				r.setUuid(rs.getString("uuid"));
				r.setBid(rs.getString("bid"));
				r.setAmount(rs.getInt("amount"));
				r.setRdate(new Date(rs.getDate("rdate").getTime()));
				rl.add(r);
			}
			m=pst.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally{
			DBUtil.close(conn, pst, rs);
		}
		System.out.println(m);
		
		return rl;
	}
	
}
